# from ppadb.client import Client as AdbClient
# from ppadb.device import Device as AdbDevice
from PySide6.QtCore import QObject, QTimer, Slot, Signal, Property, QEnum, Qt, QThread
from PySide6.QtQml import QmlElement, QmlSingleton
from PySide6.QtGui import QGuiApplication
import logging
# from .constants import *
import subprocess
import threading
from .FlashToolWorker import FlashToolWorker


# 定义 QML 模块名称和版本
QML_IMPORT_NAME = "FlashTool"
QML_IMPORT_MAJOR_VERSION = 1

@QmlElement
class FlashTool(QObject):
    adb_device_connect_state_changed = Signal()
    fastboot_device_connect_state_changed = Signal()
    flashOutput = Signal(str)
    error = Signal(str)
    
    _flashFirmware = Signal(str)
    _rebootDevice = Signal()
    _rebootToFastbootMode = Signal()
    
    flashFirmwareFinished = Signal(bool, str)
    rebootDeviceFinished = Signal(bool, str)
    rebootToFastbootModeFinished = Signal(bool, str)
    
    
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self._flashToolWorker = FlashToolWorker()
        self._workThread = QThread()
        self.app = QGuiApplication.instance()
        
        # 连接信号
        self._setup_signal_connections()
        
        # 保证线程在应用程序退出时正确退出
        self.app.aboutToQuit.connect(self._workThread.quit)
        
        self._flashToolWorker.moveToThread(self._workThread)
        self._workThread.start()
        
    def _setup_signal_connections(self):
        self._flashToolWorker.adb_device_connect_state_changed.connect(self.adb_device_connect_state_changed)
        self._flashToolWorker.fastboot_device_connect_state_changed.connect(self.fastboot_device_connect_state_changed)
        self._flashToolWorker.flashOutput.connect(self.flashOutput)
        self._flashToolWorker.error.connect(self.error)
        
        self._flashFirmware.connect(self._flashToolWorker.flashFirmware)
        self._rebootDevice.connect(self._flashToolWorker.rebootDevice)
        self._rebootToFastbootMode.connect(self._flashToolWorker.rebootToFastbootMode)
        
        
    @Property(bool, notify=adb_device_connect_state_changed)
    def adbDeviceConnected(self):
        return self._flashToolWorker.adbDeviceConnected()
    
    @Property(bool, notify=fastboot_device_connect_state_changed)
    def fastbootDeviceConnected(self):
        return self._flashToolWorker.fastbootDeviceConnected()
    
    @Property('QStringList', notify=adb_device_connect_state_changed)
    def adbDevices(self):
        return self._flashToolWorker.adbDevices()

    @Property('QStringList', notify=fastboot_device_connect_state_changed)
    def fastbootDevices(self):
        return self._flashToolWorker.fastbootDevices()
    
    @Slot()
    def rebootToFastbootMode(self):
        self._rebootToFastbootMode.emit()
    
    @Slot(str)
    def flashFirmware(self, firmware_path):
        self._flashFirmware.emit(firmware_path)

    @Slot()
    def rebootDevice(self):
        self._rebootDevice.emit()